package server.tcp;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;

import mockup.LoginMockup;
import mockup.Mockup;
import server.Server;
import server.Session;

/**
 * Handles the text flow between the client and the
 * server. Every time a message should be sent a new connection is
 * established 
 * @author daniel
 * @author Erik
 */
public class SeparateConnection implements Runnable {

	private Socket socket;
	private Session session;

	private boolean run = true;
	/**
	 * The constructor, invokes the receive method.
	 * @param socket That is connected to the server.
	 */
	public SeparateConnection(Socket socket, Session session) {
		this.socket = socket;
		this.session = session;

		Thread t = new Thread(this);
		t.start();
		
	}

	public void run() {
		try {
			while(run && socket.isConnected() && !socket.isClosed()) {
				
				ObjectInputStream receiveStream = new ObjectInputStream(socket.getInputStream());
				Serializable ser = (Serializable)receiveStream.readObject();
				
				if(Server.debugLowerLogic)
					System.out.println("SeperateConnection::run: received a " + ser.getClass().getSimpleName());
				
				if(ser instanceof Mockup) {
					
					Mockup fromClient = (Mockup) ser;
					
					if(fromClient instanceof LoginMockup)
						fromClient.setSessionId(session.getSessionID());
					
					Serializable fromServer = Server.execute(fromClient, session);
					
					if(Server.debugLowerLogic)
						System.out.println("SeparateConnection::run: sending a " + 
								((fromServer != null) ? fromServer.getClass().getSimpleName() : "null object"));
					
					ObjectOutputStream sendStream = new ObjectOutputStream(socket.getOutputStream());
					sendStream.writeObject(fromServer);

				}
				else {
					ObjectOutputStream sendStream = new ObjectOutputStream(socket.getOutputStream());
					sendStream.writeObject(null);
				}
				
				
			}

		} catch (IOException e) {
			System.err.println("SeparateConnection::run: got an I/O exception");
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.err.println("SeparateConnection::run: received an object of an unknown class");
			e.printStackTrace();
		}

				
		try {
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Server.removeSession(session);
		System.out.println("SeparateConnection::run: thread stopping the connection " + this);
		closeConnection();
	}
	
	/**
	 * closes all the connections
	 */
	public void closeConnection() {
		run = false;
	}
}
